﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.AspNetCore.SignalR;
using Volo.Abp.Users;

namespace my.abp.Application.SignalRHubs
{
	/// <summary>
	/// SignalR通讯 /hub/main
	/// </summary>
	[HubRoute("/hub/main")]
	[Authorize]
	public class OnlineHub : AbpHub
	{
		private readonly static object objLock = new object();

		private HttpContext? _httpContext;
		private ILogger<OnlineHub> _logger => LoggerFactory.CreateLogger<OnlineHub>();
		public OnlineHub(IHttpContextAccessor httpContextAccessor)
		{
			_httpContext = httpContextAccessor?.HttpContext;
		}

		/// <summary>
		/// 成功连接
		/// </summary>
		/// <returns></returns>
		public override Task OnConnectedAsync()
		{
			lock (objLock)
			{

				var name = CurrentUser.UserName;
				//var loginUser = new LoginLogEntity().GetInfoByHttpContext(_httpContext);
				SendWelcome(Context.ConnectionId, "welcome", $"欢迎您：{name},当前时间：{DateTime.Now}");
			}
			return base.OnConnectedAsync();
		}

		/// <summary>
		/// 断开连接
		/// </summary>
		/// <param name="exception"></param>
		/// <returns></returns>
		public override Task OnDisconnectedAsync(Exception exception)
		{
			lock (objLock)
			{
				var name = CurrentUser.UserName;
				Console.WriteLine($"用户{name}离开了,当前时间：{DateTime.Now}");
			}
			return base.OnDisconnectedAsync(exception);
		}

		/// <summary>
		/// 对全体发送消息
		/// </summary>
		/// <param name="test"></param>
		/// <returns></returns>
		public async Task SendAllTest(string test)
		{
			await Clients.All.SendAsync("ReceiveAllInfo", test);
		}

		/// <summary>
		/// 发送欢迎消息
		/// </summary>
		/// <param name="connectId"></param>
		/// <param name="method"></param>
		/// <param name="message"></param>
		/// <returns></returns>
		public async Task SendWelcome(string connectId, string method, string message)
		{
			await Clients.Client(connectId).SendAsync(method, message, connectId);
		}

		/// <summary>
		/// 接收客户端信息
		/// </summary>
		/// <param name="connectId"></param>
		/// <param name="userName"></param>
		/// <param name="message"></param>
		/// <returns></returns>
		[HubMethodName("SendMessage")]
		public async Task SendMessage(string connectId, string userName, string message)
		{
			Console.WriteLine($"{connectId},message={message}");

			await Clients.Client(connectId).SendAsync("receiveChat", new { userName, message });
		}
	}
}
